/*取出一个数据表的所有记录
传入参数e是包含key - value数据的对象
e._table是数据表名称
e._where:{}
e._order1..._order3:['_id','asc']
20160602:加入_where_in参数,相当于_id:db.command.in(_where_in)
*/
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const MAX_LIMIT = 100
exports.main = async (e, context) => {
  let table = e._table
  let where = e._where
  if (typeof e._where_in != 'undefined') {
    where = { _id: db.command.in(e._where_in) }
  }
  let order1 = e._order1
  let order2 = e._order2
  let order3 = e._order3
  let fields = e._fields
  // 先取出集合记录总数
  const countResult = await db.collection(table).count()
  const total = countResult.total
  // 计算需分几次取
  const batchTimes = Math.ceil(total / 100)
  // 承载所有读操作的 promise 的数组
  const tasks = []
  for (let i = 0; i < batchTimes; i++) {
    const promise = db.collection(table)
      .where(where)
      .orderBy(order1[0], order1[1])
      .orderBy(order2[0], order2[1])
      .orderBy(order3[0], order3[1])
      .skip(i * MAX_LIMIT).limit(MAX_LIMIT).field(fields).get()
    tasks.push(promise)
  }
  // 等待所有
  return (await Promise.all(tasks)).reduce((acc, cur) => {
    return {
      data: acc.data.concat(cur.data),
      errMsg: acc.errMsg,
    }
  })
}